import 'package:baselib/utils/log_util.dart';
import 'package:dio/dio.dart';

import 'errorhandle.dart';

/**
 * 拦截器
 */
class LoggingInterceptor extends Interceptor {
  DateTime? startTime;
  DateTime? endTime;

  String? requestUrl;
  @override
  onRequest(RequestOptions options, RequestInterceptorHandler handler,) {
    // onRequest(RequestOptions options,) {
    startTime = DateTime.now();
    LogUtil.d("----------Start----------");
    LogUtil.d("RequestUrl: " + options.baseUrl + options.path);
    LogUtil.d("RequestMethod: " + options.method);
    LogUtil.d("RequestHeaders:" + options.headers.toString());
    LogUtil.d("RequestContentType: ${options.contentType}");
    LogUtil.d("RequestData: ${options.data.toString()}");
    requestUrl = options.baseUrl + options.path;
    return super.onRequest(options,handler);
  }

  @override
  onResponse(Response response, ResponseInterceptorHandler handler,) {
    LogUtil.d('onResponse response=${response?.toString()}');
    endTime = DateTime.now();
    int duration = endTime!.difference(startTime??DateTime.now()).inMilliseconds;
    LogUtil.d("----------End: $duration 毫秒,url=$requestUrl----------");
    // return super.onResponse(response,);
    return super.onResponse(response,handler);
  }

  @override
  onError(DioError err, ErrorInterceptorHandler handler,) {
    // onError(DioError err,) {
    print('onError response=${err?.error}');
    print('onError response=${err?.toString()}');
    print('onError response=${err?.response.toString()}');
    LogUtil.d("----------Error,url=$requestUrl-----------");
    return super.onError(err,handler);
    // return super.onError(err,);
  }
}

class AdapterInterceptor extends Interceptor{

  @override
  void onRequest(RequestOptions options, RequestInterceptorHandler handler) {
    super.onRequest(options, handler);
  }

  @override
   onResponse(Response response, ResponseInterceptorHandler handler) {
    Response r = adapterData(response);
    super.onResponse(response, handler);
  }

  @override
  void onError(DioException err, ErrorInterceptorHandler handler) {
    super.onError(err, handler);
  }

  Response adapterData(Response response) {
    int? statusCode = response.statusCode;
    String? statusMessage = response.statusMessage;
    dynamic data = response.data;
    return response;
  }

}